package com.han.jk_mqtt

import io.netty.bootstrap.Bootstrap
import io.netty.channel.ChannelInitializer
import io.netty.channel.nio.NioEventLoopGroup
import io.netty.channel.socket.nio.NioSocketChannel
import io.netty.handler.codec.mqtt.MqttDecoder
import io.netty.handler.codec.mqtt.MqttEncoder
import io.netty.util.internal.logging.Log4JLoggerFactory
//import io.netty.handler.logging.LoggingHandler;

class MqttClient {




    init {
        val worker = NioEventLoopGroup()
        val bootstrap = Bootstrap()
        bootstrap.group(worker)
        bootstrap.channel(NioSocketChannel::class.java)
//            .channel(Log4JLoggerFactory.)
//            .handler(LoggingHandler())
            .handler(object :
            ChannelInitializer<NioSocketChannel>() {
            override fun initChannel(ch: NioSocketChannel) {
                val pipeline = ch.pipeline()
                pipeline.addLast(MqttDecoder())
                pipeline.addLast(MqttEncoder.INSTANCE)
                pipeline.addLast(MqttChannelHandler())
            }
        })
        val host="mq.tongxinmao.com"
        val port=18832
//        val host="localhost"
//        val host="127.0.0.1"
//        val port=1883
        bootstrap.connect(host,port).addListener {
            if (it.isSuccess) {
                println("连接成功")
            }else{
                println("连接失败")
            }
        }
    }
}